#!/usr/bin/env python
# -*- coding: utf-8 -*-

def foo():
    for i in range(5):
        print('i am foo %d' % i)
        yield

def bar():
    for i in range(10):
        print('i am bar %d' % i)
        yield

def spam():
    for n in range(7):
        print('i am spam %d' % n)
        yield

from collections import deque
taskqueue = deque()      #后进先出
taskqueue.append(foo())
taskqueue.append(bar())
taskqueue.append(spam())
while taskqueue:
    task = taskqueue.pop()
    try:
        next(task)
        taskqueue.appendleft(task)
    except StopIteration:
        pass